<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 合同模板 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-select v-model="query.address" placeholder="地址" class="handle-select mr10">
                    <el-option key="1" label="广东省" value="广东省"></el-option>
                    <el-option key="2" label="湖南省" value="湖南省"></el-option>
                </el-select> -->
                <el-input v-model="query.keyword" placeholder="模板名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
                <el-button type="primary" @click="handleSearchByUser">查看我创建的</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-form label-position="left" inline class="demo-table-expand">
                            <el-form-item label="模板ID">
                                <span>{{ scope.row.templateId }}</span>
                            </el-form-item>
                            <el-form-item label="模板名称">
                                <span>{{ scope.row.templateName }}</span>
                            </el-form-item>
                            <el-form-item label="合同类型">
                                <span>{{ scope.row.contractType }}</span>
                            </el-form-item>
                            <el-form-item label="所属部门">
                                <span>{{ scope.row.depart }}</span>
                            </el-form-item>
                            <el-form-item label="甲方公司">
                                <span>{{ scope.row.companiesA }}</span>
                            </el-form-item>
                            <el-form-item label="乙方公司">
                                <span>{{ scope.row.companiesB }}</span>
                            </el-form-item>
                            <el-form-item label="合同金额">
                                <span>￥{{ scope.row.contractAmount }}</span>
                            </el-form-item>
                            <el-form-item label="创建人">
                                <span>{{ scope.row.createUser }}</span>
                            </el-form-item>
                            <el-form-item label="创建时间">
                                <span>{{ scope.row.createTime }}</span>
                            </el-form-item>
                            <el-form-item label="负责人/手机">
                                <span>{{ scope.row.contactPerson + '/' + scope.row.contactPhone }}</span>
                            </el-form-item>
                            <div>
                                <el-form-item
                                    v-for="(item, index) in scope.row.externList"
                                    :key="index"
                                    :label="'字段' + index + ' ' + item.name"
                                >
                                    <span>{{ item.value }}</span>
                                </el-form-item>
                            </div>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="templateId" label="ID" align="left" show-overflow-tooltip></el-table-column>
                <el-table-column prop="templateName" label="模板名称"></el-table-column>
                <el-table-column prop="createUser" label="创建人"></el-table-column>
                <el-table-column prop="createTime" label="创建时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page.sync="pageParams.currentPage"
                    :page-size.sync="pageParams.pageSize"
                    :page-count="pageParams.totalElements"
                    :total="pageParams.totalElements"
                    @current-change="getTemplateData"
                ></el-pagination>
            </div>
        </div>

        <el-dialog title="添加" :visible.sync="addVisible" width="90%">
            <div>
                <el-form ref="form" :model="form" label-width="120px" label-position="left" :rules="rules">
                    <div class="form-box">
                        <el-form-item prop="templateName" label="模板名称">
                            <el-input v-model="form.templateName"></el-input>
                        </el-form-item>
                        <el-form-item prop="contractType" label="合同类型">
                            <el-select v-model="form.contractType" placeholder="请选择">
                                <el-option
                                    v-for="item in contractTypes"
                                    :key="item.typeId"
                                    :label="item.typeName"
                                    :value="item.typeId"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="depart" label="所属部门">
                            <el-select v-model="form.depart" placeholder="请选择">
                                <el-option
                                    v-for="item in departs"
                                    :key="item.departId"
                                    :label="item.departName"
                                    :value="item.departId"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="contactInfo" label="负责人/电话">
                            <el-select v-model="form.contactInfo" placeholder="请选择">
                                <el-option
                                    v-for="item in users"
                                    :key="item.id"
                                    :label="item.username + '/' + item.phone"
                                    :value="item.username + '/' + item.phone"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="companiesA" label="甲方公司">
                            <el-select v-model="form.companiesA" multiple placeholder="请选择">
                                <el-option
                                    v-for="item in companies"
                                    :key="item.companyName"
                                    :label="item.companyName"
                                    :value="item.companyId"
                                    :disabled="form.companiesB.some((e) => e == item.companyId) === true"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="form-box">
                        <el-form-item label="合同金额">
                            <el-input-number
                                size="medium"
                                v-model="form.contractAmount"
                                :precision="2"
                                :step="1"
                                :min="0"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item prop="externString" label="额外字段">
                            <el-input disabled v-model="form.externString" style="width: 70%"></el-input>
                            <el-button type="primary" style="margin: 0px 0px 0px 10px" @click="handleEditExtern">添加</el-button>
                        </el-form-item>
                        <el-form-item label="创建人员" style="width: 50%">
                            <el-input v-model="form.createUser" disabled></el-input>
                        </el-form-item>

                        <el-form-item prop="companiesB" label="乙方公司">
                            <el-select v-model="form.companiesB" multiple placeholder="请选择">
                                <el-option
                                    v-for="item in companiesB"
                                    :key="item.companyId"
                                    :label="item.companyName"
                                    :value="item.companyId"
                                    :disabled="form.companiesA.some((e) => e === item.companyId) === true"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
                <div style="text-align: center">
                    <el-button type="primary" @click="handleSaveEdit">添加</el-button>
                    <el-button @click="addVisible = false">取消</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="90%">
            <div>
                <el-form ref="form" :model="form" label-width="120px" label-position="left" :rules="rules">
                    <div class="form-box">
                        <el-form-item prop="templateName" label="模板名称">
                            <el-input disabled v-model="form.templateName"></el-input>
                        </el-form-item>
                        <el-form-item prop="contractType" label="合同类型">
                            <el-select v-model="form.contractType" placeholder="请选择">
                                <el-option
                                    v-for="item in contractTypes"
                                    :key="item.typeId"
                                    :label="item.typeName"
                                    :value="item.typeId"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="depart" label="所属部门">
                            <el-select v-model="form.depart" placeholder="请选择">
                                <el-option
                                    v-for="item in departs"
                                    :key="item.departId"
                                    :label="item.departName"
                                    :value="item.departId"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="contactInfo" label="负责人/电话">
                            <el-select v-model="form.contactInfo" placeholder="请选择">
                                <el-option
                                    v-for="item in users"
                                    :key="item.id"
                                    :label="item.username + '/' + item.phone"
                                    :value="item.username + '/' + item.phone"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="companiesA" label="甲方公司">
                            <el-select v-model="form.companiesA" multiple placeholder="请选择">
                                <el-option
                                    v-for="item in companies"
                                    :key="item.companyName"
                                    :label="item.companyName"
                                    :value="item.companyId"
                                    :disabled="form.companiesB.some((e) => e == item.companyId) === true"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="form-box">
                        <el-form-item label="合同金额">
                            <el-input-number
                                size="medium"
                                v-model="form.contractAmount"
                                :precision="2"
                                :step="1"
                                :min="0"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item prop="externString" label="额外字段">
                            <el-input disabled v-model="form.externString" style="width: 70%"></el-input>
                            <el-button type="primary" style="margin: 0px 0px 0px 10px" @click="handleEditExtern">添加</el-button>
                        </el-form-item>
                        <el-form-item label="创建人员" style="width: 50%">
                            <el-input v-model="form.createUser" disabled></el-input>
                        </el-form-item>

                        <el-form-item prop="companiesB" label="乙方公司">
                            <el-select v-model="form.companiesB" multiple placeholder="请选择">
                                <el-option
                                    v-for="item in companiesB"
                                    :key="item.companyId"
                                    :label="item.companyName"
                                    :value="item.companyId"
                                    :disabled="form.companiesA.some((e) => e === item.companyId) === true"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
                <div style="text-align: center">
                    <el-button type="primary" @click="handleSaveEdit">编辑</el-button>
                    <el-button @click="editVisible = false">取消</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="额外字段" :visible.sync="externVisible" width="50%">
            <el-form :inline="true" :model="form" label-width="80px">
                <div v-for="(item, index) in form.externList" :key="item.key">
                    <el-form-item
                        :label="'字段' + index"
                        :prop="'externList.' + index + '.name'"
                        :rules="[{ required: true, message: '字段不能为空', trigger: 'blur' }]"
                    >
                        <el-input v-model="item.name" placeholder="输入字段名"> </el-input>
                    </el-form-item>
                    <el-form-item
                        :label="'内容' + index"
                        :prop="'externList.' + index + '.value'"
                        :rules="[{ required: true, message: '内容不能为空', trigger: 'blur' }]"
                    >
                        <el-input v-model="item.value" placeholder="输入内容"> </el-input>
                    </el-form-item>
                    <el-button style="margin: 0px 10px" @click.prevent="removeExtern(item)">删除</el-button>
                </div>
                <div style="text-align: center">
                    <el-form-item>
                        <el-button type="primary" @click="closeExtern">确定</el-button>
                        <el-button @click="addExtern">新增</el-button>
                        <el-button @click="resetExtern">重置</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { dateToString, getFromDateAndTime } from '../../util/DateUtil.js';
import * as api from '@/api/index';
export default {
    name: 'contractTemplate',
    data() {
        var checkExtern = (rule, value, callback) => {
            let list = this.form.externList;
            let len = list.length;
            for (let i = 0; i < len; i++) {
                if (list[i].name === '' || list[i].value === '') {
                    callback(new Error('请完善字段'));
                }
                if (list[i].name !== '' && list[i].value !== '') {
                    for (let j = 0; j < len && i !== j; j++) {
                        if (list[i].name === list[j].name) {
                            callback(new Error('字段名称存在重复'));
                        }
                    }
                }
            }
            callback();
        };
        return {
            query: {
                keyword: ''
            },
            isSearchUser: false,
            contract: [],
            tableData: [],
            pageParams: {
                currentPage: 1,
                pageSize: 10,
                totalElements: 20,
                totalPages: 1
            },
            loginUser: {
                userId: '',
                username: '',
                usertype: 0
            },
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            externVisible: false,
            pageTotal: 4,
            form: {
                templateId: '',
                templateName: '',
                contractType: '',
                depart: '',
                companiesA: [],
                companiesB: [],
                startTime: '',
                endTime: '',
                contractAmount: '',
                contactPerson: '',
                contactPhone: '',
                contactInfo: '',
                createUser: '',
                startTime1: '',
                startTime2: '',
                endTime1: '',
                endTime2: '',
                externList: [
                    {
                        name: '',
                        value: ''
                    }
                ],
                deleted: 0
            },
            originForm: {},
            rules: {
                templateName: [{ required: true, message: '请输入合同名', trigger: 'blur' }],
                contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
                companiesA: [{ required: true, message: '请选择甲方公司', trigger: 'change' }],
                companiesB: [{ required: true, message: '请选择乙方公司', trigger: 'change' }],
                contactInfo: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                depart: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
                passed: [{ required: true, message: '请选择审批类型', trigger: 'blur' }],
                completed: [{ required: true, message: '是否完成', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
                externString: [{ validator: checkExtern, trigger: ['blur', 'change'] }],
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
            },
            contractTypes: [],
            departs: [],
            users: [],
            companies: [],
            companiesA: [],
            companiesB: [],
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
        this.originForm = this.form;
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            this.getTemplateData();
            this.getContractTypeData();
            this.getDepartData();
            this.getCompanyData();
            this.getUserData();
            this.loginUser.userId = localStorage.getItem('userId');
            this.loginUser.username = localStorage.getItem('username');
            this.loginUser.usertype = parseInt(localStorage.getItem('usertype'));
        },
        getTemplateData() {
            let currentPage = this.pageParams.currentPage;
            let pageSize = this.pageParams.pageSize;
            let params = new Object();
            if (this.isSearchUser === false) {
                params.keyword = this.query.keyword;
            } else {
                params.createUser = this.loginUser.username;
            }
            // console.log(params);
            api.searchAllPageByQuery(currentPage, pageSize, params)
                .then((res) => {
                    console.log(res);
                    if (res.code === 200) {
                        this.tableData = res.data.content;
                        this.pageParams.currentPage = res.data.currentPage;
                        this.pageParams.pageSize = res.data.pageSize;
                        this.pageParams.totalElements = res.data.totalElements;
                        this.pageParams.totalPages = res.data.totalPages;
                    }
                    if (res.code === 400 && this.isSearchUser == true) {
                        this.tableData = [];
                        this.isSearchUser = false;
                    }
                })
                .then((err) => {
                    console.log(err);
                });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        handleSearchByUser() {
            this.isSearchUser = true;
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    api.deleteTemplateById(row.templateId)
                        .then((res) => {
                            if (res.code === 200) {
                                this.$message.success('删除成功');
                            } else {
                                this.$message.error('删除失败');
                            }
                            this.getData();
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        handleAdd() {
            this.form = new Object();
            this.form = this.originForm;
            this.form.createUser = this.loginUser.username;
            this.addVisible = true;
        },
        // 编辑操作
        handleEdit(index, row) {
            this.getFormDataFromRow(index, row);
            this.idx = index;
            this.editVisible = true;
        },
        handleCancel() {
            this.editVisible = false;
            this.addVisible = false;
        },
        getFormDataFromRow(index, row) {
            let companiesA = [];
            this.companies.forEach((item) => {
                if (row.companiesA.split(',').some((e) => e == item.companyName)) {
                    companiesA.push(item.companyId);
                }
            });
            let companiesB = [];
            this.companies.forEach((item) => {
                if (row.companiesB.split(',').some((e) => e == item.companyName)) {
                    companiesB.push(item.companyId);
                }
            });

            let depart = '';
            for (var i in this.departs) {
                let item = this.departs[i];
                if (item.departName === row.depart) {
                    depart = item.departId;
                    break;
                }
            }
            let contractType = '';
            for (var i in this.contractTypes) {
                let item = this.contractTypes[i];
                if (item.typeName === row.contractType) {
                    contractType = item.typeId;
                    break;
                }
            }
            let createUserId = '';
            for (var i in this.users) {
                let item = this.users[i];
                if (item.username === row.createUser) {
                    createUserId = item.userId;
                    break;
                }
            }
            this.form.templateId = row.templateId;
            this.form.templateName = row.templateName;
            this.form.depart = depart;
            this.form.createUserId = createUserId;
            this.form.contractType = contractType;
            this.form.contactPerson = row.contactPerson;
            this.form.contactPhone = row.contactPhone;
            this.form.contactInfo = row.contactPerson + '/' + row.contactPhone;
            this.form.companiesA = companiesA;
            this.form.companiesB = companiesB;
            this.form.contractAmount = row.contractAmount;
            this.form.externList = row.externList;
            this.form.createUser = row.createUser;
            this.getExternString();
        },
        convertFormToParams() {
            let companiesA = [];
            this.form.companiesA.forEach((item) => {
                companiesA.push({
                    companyId: item
                });
            });
            let companiesB = [];
            this.form.companiesB.forEach((item) => {
                companiesB.push({
                    companyId: item
                });
            });

            let params = new Object();
            if (this.editVisible === true) {
                params.templateId = this.form.templateId;
            }
            if (this.addVisible === true) {
                params.createUser = {
                    userId: this.loginUser.userId
                };
            }
            params.contactPerson = this.form.contactInfo.split('/')[0];
            params.contactPhone = this.form.contactInfo.split('/')[1];
            params.templateName = this.form.templateName;
            params.contractType = {
                typeId: this.form.contractType
            };
            params.depart = {
                departId: this.form.depart
            };

            params.companiesA = companiesA;
            params.companiesB = companiesB;
            params.contractAmount = this.form.contractAmount;
            params.externList = this.form.externList;
            // console.log(this.form.passed)
            return params;
        },
        handleSaveEdit() {
            let params = this.convertFormToParams();
            this.$refs.form.validate((vaild) => {
                if (vaild) {
                    api.saveTemplate(params)
                        .then((res) => {
                            if (res.code === 200) {
                                this.$message.success(res.msg);
                                this.editVisible = false;
                                this.addVisible = false;
                                this.getData();
                            } else {
                                if (this.editVisible === true) {
                                    this.$message.error('编辑失败');
                                }
                                if (this.addVisible === true) {
                                    this.$message.error('添加失败');
                                }
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                }
            });
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        resetExtern() {
            this.form.externList = [
                {
                    name: '',
                    value: ''
                }
            ];
            this.getExternString();
        },
        closeExtern() {
            this.$refs.form.validate((vaild) => {});
            this.externVisible = false;
            this.getExternString();
        },
        handleEditExtern() {
            this.externVisible = true;
        },
        removeExtern(item) {
            var index = this.form.externList.indexOf(item);
            if (index !== -1) {
                this.form.externList.splice(index, 1);
            }
            this.getExternString();
        },
        addExtern() {
            this.form.externList.push({
                name: '',
                value: '',
                key: Date.now()
            });
        },
        getExternString() {
            let list = this.form.externList;
            let string = '';
            if (list.length > 1) {
                for (let i = 0; i < list.length - 1; i++) {
                    //console.log(list[i].value);
                    string += list[i].name + ':' + list[i].value + ',';
                }

                string += list[list.length - 1].name + ':' + list[list.length - 1].value;
            }
            if (list.length === 1) {
                string += list[list.length - 1].name + ':' + list[list.length - 1].value;
            }
            this.$set(this.form, 'externString', string);
            // console.log(string);
            // console.log(1);
            // console.log(this.form.externString);
        },
        getFormData() {
            this.getCompanyData();
            this.getContractTypeData();
            this.getDepartData();
            this.getUserData();
        },
        getCompanyData() {
            api.getAllCompanyList()
                .then((res) => {
                    if (res.code === 200) {
                        this.companies = res.data;
                        this.companiesA = this.companies;
                        this.companiesB = this.companies;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getContractTypeData() {
            api.getAllContractTypeList()
                .then((res) => {
                    if (res.code === 200) {
                        this.contractTypes = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getContractTypeData');
                    console.log(err);
                });
        },
        getDepartData() {
            api.getAllDepartList()
                .then((res) => {
                    if (res.code === 200) {
                        this.departs = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getDepartData');
                    console.log(err);
                });
        },
        getUserData() {
            api.getAllUserList()
                .then((res) => {
                    if (res.code === 200) {
                        this.users = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getUserData');
                    console.log(err);
                });
        }
    }
};
</script>

<style scoped>
.demo-table-expand {
    font-size: 0;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.form-box {
    display: inline-block;
    margin: 10px 30px;
    width: 45%;
}
</style>
